//
//  CategoriesViewController.m
//  iWeddingDirectory
//
//  Created by Tung Ngo on 5/30/12.
//  Copyright (c) 2012 Home. All rights reserved.
//

#import "CategoriesViewController.h"
#import "API.h"
#import "Category.h"
#import "PostsViewController.h"
#import "SendInquiryViewController.h"

@implementation CategoriesViewController

@synthesize categories;
//@synthesize buttonInquiryToAll;
//@synthesize buttonCancel;
@synthesize inquiryMode;
@synthesize ids;
@synthesize subCategoryMode;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
        UITabBarItem *item = [[UITabBarItem alloc] initWithTitle:@"Categories" image:[UIImage imageNamed:@"category.png"] tag:0];
        self.tabBarItem = item;
        [item release];
        subCategoryMode = NO;
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)dealloc
{
    [categories release];
    //[buttonInquiryToAll release];
    //[buttonCancel release];
    [ids release];
    [super dealloc];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    [self.navigationController.navigationBar setBarStyle:UIBarStyleBlackOpaque];
    
    self.title = @"Categories";
    
    categories = [[NSMutableArray alloc] initWithCapacity:0];
    
    //buttonInquiryToAll = [[UIBarButtonItem alloc] initWithTitle:@"Inquiry To All" style:UIBarButtonItemStyleDone target:self action:@selector(onButtonInquiryToAllClicked:)];
    //self.navigationItem.rightBarButtonItem = buttonInquiryToAll;
    
    //buttonCancel = [[UIBarButtonItem alloc] initWithTitle:@"Cancel" style:UIBarButtonItemStyleDone target:self action:@selector(onButtonCancelClicked:)];
    
    ids = [[NSMutableArray alloc] initWithCapacity:0];
    
    UIActivityIndicatorView *waitingIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    [waitingIndicator setTag:1000];
    [waitingIndicator setCenter:CGPointMake(160, 181)];
    [self.view addSubview:waitingIndicator];
    [waitingIndicator startAnimating];
    [waitingIndicator release];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onCategoriesReceived:) name:kCategoriesReceivedNotification object:nil];
    
    API *api = [API sharedInstance];
    [api getCategories];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [categories count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    // Configure the cell...
    Category *category = [categories objectAtIndex:indexPath.row];
    cell.textLabel.text = category.title;// stringByAppendingFormat:@" [%d]",category.postCount];
    if (inquiryMode) {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    else {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    
    return cell;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    Category *category = [categories objectAtIndex:indexPath.row];
    NSLog(@"this row has children? %d", category.hasChildren);
    if( category.hasChildren == NO ){
        //Top category.
        if (inquiryMode) {
    //        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    //        Category *category = [categories objectAtIndex:indexPath.row];
    //        if ([ids containsObject:[NSNumber numberWithInt:category.categoryId]]) {
    //            [ids removeObject:[NSNumber numberWithInt:category.categoryId]];
    //            cell.accessoryType = UITableViewCellAccessoryNone;
    //        }
    //        else {
    //            [ids addObject:[NSNumber numberWithInt:category.categoryId]];
    //            cell.accessoryType = UITableViewCellAccessoryCheckmark;
    //        }
    //        if ([ids count] > 0) {
    //            buttonInquiryToAll.title = @"Send Inquiry";
    //        }
    //        else {
    //            buttonInquiryToAll.title = @"Inquiry To All";
    //        }
        }
        else {
            PostsViewController *vcPosts = [[PostsViewController alloc] initWithStyle:UITableViewStylePlain];
            [vcPosts setCategory:category];
            [self.navigationController pushViewController:vcPosts animated:YES];
            [vcPosts release];
        }
    } else {
        //CategoriesViewController *cvc = [[CategoriesViewController alloc] initWithStyle:UITableViewStylePlain];
        //Call API again:
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onSubCategoriesReceived:) name:kSubCategoriesReceivedNotification object:nil];
        API *api = [API sharedInstance];
        [api getSubCategories];
        self.subCategoryMode = YES;
        //[cvc setSubCategoryMode:YES];
        //[cvc release];
        
    }
}

#pragma mark - On Categories Received

- (void)onCategoriesReceived:(NSNotification *)notification
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kCategoriesReceivedNotification object:nil];
    
    UIActivityIndicatorView *waitingIndicator = (UIActivityIndicatorView *)[self.view viewWithTag:1000];
    [waitingIndicator stopAnimating];
    
    NSDictionary *result = [notification userInfo];
    NSArray *_categories = [result objectForKey:@"categories"];
    for (NSDictionary *_category in _categories) {
        int parent_id = [[_category objectForKey:@"parent"] intValue];
        Category *category = [[Category alloc] init];
        int categoryId = [[_category objectForKey:@"id"] intValue];
        NSString *title = [_category objectForKey:@"title"];
        int postCount = [[_category objectForKey:@"post_count"] intValue];
        NSString *description = [_category objectForKey:@"description"];
        category.categoryId = categoryId;
        category.title = [title stringByReplacingOccurrencesOfString:@"&amp;" withString:@"&" options:NSCaseInsensitiveSearch range:NSMakeRange(0, title.length)];
        category.postCount = postCount;
        category.description = description;
        category.parentId = parent_id;
        category.hasChildren = NO;
        //NSMutableArray *subCategoryList = [[NSMutableArray alloc] initWithCapacity:0];
        if( parent_id != 0 ){
            for( Category *tempcat in categories ){ 
                if( tempcat.categoryId == parent_id ){
                    tempcat.hasChildren = YES;
                    break;
                }
            }
        } else //( parent_id == 0 )
            [categories addObject:category];
        [category release];
//        [subCategoryList release];
    }
    [self.tableView reloadData];
}

- (void)onSubCategoriesReceived:(NSNotification *)notification
{
    self.title = @"Sub Categories";
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonSystemItemDone target:self action:@selector(onBackButtonClicked)];
    self.navigationItem.leftBarButtonItem = backButton;
    [backButton release];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kCategoriesReceivedNotification object:nil];
    
    UIActivityIndicatorView *waitingIndicator = (UIActivityIndicatorView *)[self.view viewWithTag:1000];
    [waitingIndicator stopAnimating];
    
    [categories removeAllObjects];
//    [self.tableView reloadData];
    
    NSDictionary *result = [notification userInfo];
    NSArray *_categories = [result objectForKey:@"categories"];
    for (NSDictionary *_category in _categories) {
        int parent_id = [[_category objectForKey:@"parent"] intValue];
        Category *category = [[Category alloc] init];
        int categoryId = [[_category objectForKey:@"id"] intValue];
        NSString *title = [_category objectForKey:@"title"];
        int postCount = [[_category objectForKey:@"post_count"] intValue];
        NSString *description = [_category objectForKey:@"description"];
        category.categoryId = categoryId;
        category.title = [title stringByReplacingOccurrencesOfString:@"&amp;" withString:@"&" options:NSCaseInsensitiveSearch range:NSMakeRange(0, title.length)];
        category.postCount = postCount;
        category.description = description;
        category.parentId = parent_id;
        category.hasChildren = NO;
        //NSMutableArray *subCategoryList = [[NSMutableArray alloc] initWithCapacity:0];
        if( parent_id != 0 ){
            [categories addObject:category];
        } 
        [category release];
        //        [subCategoryList release];
    }
    [self.tableView reloadData];
}

-(void) onBackButtonClicked
{
    self.subCategoryMode = NO;
    [self viewDidLoad];
}

#pragma mark - Button Clicked Handlers

//- (void)onButtonCancelClicked:(id)sender
//{
//    self.navigationItem.leftBarButtonItem = nil;
//    inquiryMode = NO;
//    [ids removeAllObjects];
//    [self.tableView reloadData];
//}
//
//- (void)onButtonInquiryToAllClicked:(id)sender
//{
//    self.navigationItem.leftBarButtonItem = buttonCancel;
//    if (inquiryMode == NO) {
//        inquiryMode = YES;
//        [self.tableView reloadData];
//    }
//    else if ([ids count] > 0) {
//        NSString *_ids = [ids componentsJoinedByString:@","];
//        SendInquiryViewController *vcSendInquiry = [[SendInquiryViewController alloc] init];
//        vcSendInquiry.ids = _ids;
//        [self.navigationController pushViewController:vcSendInquiry animated:YES];
//        [vcSendInquiry release];
//    }
//}

@end
